<!-- Login -->
<template>
  <validate-form @form-submit="onSubmit">
    <div class="mb-3">
      <label for="exampleInputEmail1" class="form-label">邮箱地址</label>
      <validate-input :rules="emailRules" v-model="emailRef.val" type="email" placeholder="请输入邮箱" class="myEmail"></validate-input>
    </div>
    <div class="mb-3">
      <label for="exampleInputPassword1" class="form-label">密码</label>
      <validate-input :rules="pwdRules" v-model="pwdRef.val" type="password" placeholder="请输入密码" class="mypwd"></validate-input>
    </div>

    <template #submit>
      <span class="btn btn-danger">Submit</span>
    </template>
  </validate-form>
</template>

<script lang='ts'>
import { defineComponent, PropType, computed, reactive } from "vue";
import { useStore } from 'vuex'
import ValidateForm from "@/components/ValidateForm.vue";
import ValidateInput, { RulesProp } from "@/components/ValidateInput.vue";
import { useRouter } from 'vue-router'
import createMessage from '@/components/CreateMessage'
export default defineComponent({
  name: "login",
  props: {},
  components: {
    ValidateInput,
    ValidateForm,
  },

  setup(props) {
    const emailRef = reactive({
      val: "ma@163.com",
      error: false,
      message: "",
    });

    emailRef.val = "maping6462@163.com";

    const pwdRef = reactive({
      val: "123456",
      error: false,
      message: "",
    });

    const emailRules: RulesProp = [
      { type: "required", message: "电子邮箱地址不能为空" },
      { type: "email", message: "请输入正确的电子邮箱格式" },
    ];

    const pwdRules: RulesProp = [
      { type: "required", message: "密码不能为空" },
      { type: "password", message: "请输入正确的密码" },
    ];

    const router = useRouter();
    const store = useStore();
    const onSubmit = (res: boolean) => {
      // console.log("onSubmit-login--res==", res);
      setTimeout(() => {
        if(res) {
          const payload = {
            email: emailRef.val,
            password: pwdRef.val
          }
          store.dispatch("loginAndFetch", payload).then(res => {
            console.log("res===login", res);
            createMessage("登录成功", 'success')
            setTimeout(() => {
              router.push({path: '/'})
            },2000)
          }).catch(e => {
            // 模拟登录出错
            // console.log("loginAndFetch11==",e);
            // const error = e.data;
            // setTimeout(() => {
            //     store.commit('setError', {status: true, message: error.message})
            //     store.commit("setLoading", false)
            // }, 1200)
          })
        }else {

          // TODO,登录失败清空input值
          console.log("login error");
          emailRef.val = "";
          pwdRef.val = "";
        }
      }, 1000);
    };

    return {
      emailRef,
      emailRules,
      pwdRef,
      pwdRules,
      onSubmit,
    };
  },
});
</script>
<style lang='scss' scoped>
</style>